package com.flyduck.mall.pms.h5.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.flyduck.mall.common.upload.manager.UploadManager;
import com.flyduck.mall.pms.domain.PmsComment;
import com.flyduck.mall.pms.domain.PmsProduct;
import com.flyduck.mall.pms.h5.service.H5CommentService;
import com.flyduck.mall.pms.h5.vo.H5CommentDetailsRespVO;
import com.flyduck.mall.pms.h5.vo.H5CommentPostReqVO;
import com.flyduck.mall.pms.h5.vo.H5CommentRespVO;
import com.flyduck.mall.pms.mapper.PmsCommentMapper;
import com.flyduck.mall.pms.mapper.PmsProductMapper;

import com.flyduck.mall.common.core.utils.BeanUtils;
import com.flyduck.mall.ums.api.RemoteUserService;
import com.flyduck.mall.ums.api.vo.RemoteUserRespVO;
import com.flyduck.ss.common.core.exception.ServiceException;
import com.flyduck.ss.common.core.utils.StringUtils;
import com.flyduck.mall.common.mybatis.utils.PageUtils;
import com.flyduck.mall.oms.api.constant.OrderConstant;
import com.flyduck.mall.oms.api.RemoteOrderService;
import com.flyduck.mall.oms.api.RemoteOrderItemService;
import com.flyduck.mall.oms.api.vo.RemoteOrderItemRespVO;
import com.flyduck.mall.oms.api.vo.RemoteOrderItemUpdateReqVO;
import com.flyduck.mall.oms.api.vo.RemoteOrderRespVO;
import com.flyduck.ss.common.satoken.utils.LoginHelper;
import com.flyduck.ss.system.api.model.LoginUser;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @program: vueshop
 * @description:
 * @author: flyduck
 * @create: 2024-05-23 21:38
 **/
@Service
public class H5CommentServiceImpl implements H5CommentService {

    @Resource
    private PmsCommentMapper pmsCommentMapper;
    @Resource
    private UploadManager uploadManager;
    @Resource
    private PmsProductMapper pmsProductMapper;
    @DubboReference
    private RemoteOrderService remoteOrderService;
    @DubboReference
    private RemoteOrderItemService remoteOrderItemService;
    @DubboReference
    private RemoteUserService remoteUserService;

    @Override
    public Page<H5CommentRespVO> getCommentPageByProductId(Page page, Long productId) {
        Page<PmsComment> appCommentPage = pmsCommentMapper.selectPage(page,
                new LambdaQueryWrapper<PmsComment>()
                        .eq(PmsComment::getProductId,productId)
                        .orderByDesc(PmsComment::getCreateTime)
        );

        Page<H5CommentRespVO> h5CommentRespVOPage = PageUtils.convert(appCommentPage, H5CommentRespVO.class);
        for (H5CommentRespVO h5CommentRespVO : h5CommentRespVOPage.getRecords()) {
            RemoteUserRespVO remoteUserRespVO = remoteUserService.getUserById(h5CommentRespVO.getUserId());
            h5CommentRespVO.setUsername(remoteUserRespVO.getUsername());
            h5CommentRespVO.setUserAvatar(remoteUserRespVO.getAvatar());
        }
        return h5CommentRespVOPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long postComment(MultipartFile[] pics, H5CommentPostReqVO h5CommentPostReqVO) {
        Long userId = LoginHelper.getUserId();
        //1、条件判断
        RemoteOrderItemRespVO remoteOrderItemRespVO = remoteOrderItemService.getOrderItemById(h5CommentPostReqVO.getOrderItemId());
        if(remoteOrderItemRespVO.getCommentId() != null){
            throw new ServiceException("请勿重复评论");
        }
        RemoteOrderRespVO remoteOrderRespVO = remoteOrderService.getOrderById(remoteOrderItemRespVO.getOrderId());
        if(remoteOrderRespVO == null){
            throw new ServiceException("订单不存在");
        }
        if (!userId.equals(remoteOrderRespVO.getUserId())) {
            throw new ServiceException("无权限操作该订单");
        }
        if (OrderConstant.OrderStatus.COMPLETED.getCode() != remoteOrderRespVO.getOrderStatus()) {
            throw new ServiceException("该订单无法评论");
        }

        //2、图片处理
        List<String> picUrls = new ArrayList<>();
        if(ArrayUtil.isNotEmpty(pics)){
            try {
                picUrls = uploadManager.upload(pics);
            } catch (IOException e) {
                e.printStackTrace();
                throw new ServiceException("图片上传失败");
            }
        }

        //3、保存评论
        PmsComment pmsComment = new PmsComment();
        pmsComment.setUserId(userId);
        pmsComment.setProductId(remoteOrderItemRespVO.getProductId());
        pmsComment.setOrderItemId(remoteOrderItemRespVO.getId());
        pmsComment.setOrderId(remoteOrderRespVO.getId());
        pmsComment.setContent(h5CommentPostReqVO.getContent());
        pmsComment.setScore(h5CommentPostReqVO.getScore());
        pmsComment.setImages(StringUtils.join(";", picUrls));
        pmsComment.setCreateTime(new Date());
        pmsCommentMapper.insert(pmsComment);

        //4、更新订单明细的评论id和评论时间
        RemoteOrderItemUpdateReqVO remoteOrderItemUpdateReqVO = new RemoteOrderItemUpdateReqVO();
        remoteOrderItemUpdateReqVO.setId(remoteOrderItemRespVO.getId());
        remoteOrderItemUpdateReqVO.setCommentId(pmsComment.getId());
        remoteOrderItemUpdateReqVO.setCommentTime(new Date());
        remoteOrderItemService.updateOrderItem(remoteOrderItemUpdateReqVO);

        //5、商品评论数量+1
        pmsProductMapper.update(
                new LambdaUpdateWrapper<PmsProduct>()
                 .eq(PmsProduct::getId,remoteOrderItemRespVO.getProductId())
                .setSql("comments = comments + 1")
        );

        return pmsComment.getId();

    }

    @Override
    public H5CommentDetailsRespVO getCommentDetailsById(Long id) {
        PmsComment pmsComment = pmsCommentMapper.selectById(id);
        return BeanUtils.toBean(pmsComment, H5CommentDetailsRespVO.class);

    }
}
